#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "msgq.h"
#include "tools.h"

Ctos ctos;
Stoc stoc;

void save_acc(void)
{
	char path[PATH_MAX];
	Account temp;
	sprintf(path,"%s/%u",ACC_PATH,ctos.acc.id);
	pf("acc path:%s\n",path);
	int fd = open(path,O_RDONLY);
	if(ERROR == fd)
	{
		perror("open acc");
		strcpy(stoc.str,"未找到该用户，请确认账号");
	}
	else
	{
		read(fd,&temp,sizeof(Account));
		close(fd);
		if(ctos.acc.money > 0)
		{
			temp.money += ctos.acc.money;
			strcpy(stoc.str,"存钱成功");
		}
		else
		{
			strcpy(stoc.str,"不能输入0及0以下的数字");
		}
	}
	int fd1 = open(path,O_WRONLY);
	write(fd1,&temp,sizeof(Account));
	close(fd1);
	stoc_send(&stoc);
}

int main()
{
	init_msgq();
	for(;;)
	{
		ctos_recv(&ctos,TYPE_SAVE);
		stoc.type = ctos.pid;
		save_acc();
	}
}
